package com.softWang.file.util.impl;

import com.softWang.common.utils.WebUtils;
import com.softWang.file.mapper.FileManageMapper;
import com.softWang.file.po.FileManage;
import com.softWang.file.util.IFileSaveUtil;
import com.softWang.file.util.MimeTypeUtils;
import com.softWang.file.util.ftp.FTPUtils;
import com.softWang.file.vo.fileManage.FileSaveResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Component("FileSaveUtilFTPImpl")
public class FileSaveUtilFTPImpl implements IFileSaveUtil {
    @Resource
    private FileManageMapper fileManageMapper;
    @Autowired
    private FTPUtils ftpUtils;
    @Value("${ftp.basepath}")
    private String basepath;

    @Value("${file.fileSaveType}")
    private  String fileSaveType;

    @Override
    public FileSaveResult saveFile(MultipartFile file, String subDir, String fileName) throws Exception{
        String dir = basepath + "/" + subDir+"/";
        String result = ftpUtils.uploadToFtp(file.getInputStream(),fileName,dir);
        if(result == null || result.equals("")){
            return  null;
        }
        FileSaveResult saveResult = new FileSaveResult();
        saveResult.setFileUrl(null);
        return saveResult;
    }

    @Override
    public String getFileUrl(FileManage baseFile) throws Exception {
        String fileUrl = WebUtils.getDomain() + "/file/download/downFile?fileId="+baseFile.getFileId();
        return fileUrl;
    }

    @Override
    public void deleteFile(FileManage baseFile) throws Exception {
        String dir = basepath + "/" + baseFile.getFileDiskPath();
        ftpUtils.deleteFile(dir,baseFile.getFileName());
    }

    @Override
    public  void downFile(FileManage baseFile, HttpServletResponse response)throws Exception{
        String dir = basepath + "/" + baseFile.getFileDiskPath();
        byte[] data = ftpUtils.downloadFileByByteArray(baseFile.getFileName(),dir);
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(baseFile.getOriName(), "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(data);
        outputStream.close();
    }

}
